<?php
App::uses('AppController', 'Controller');
/**
 * CorUsers Controller
 *
 * @property CorUser $CorUser
 */
class UsersController extends AppController {
	var $uses = array('cor_User');
	
	public function view($id = null) 
	{
		
		$this->cor_User->id = $id;		
		if(!$this->cor_User->exists())
		{
			throw new NotFoundException(__('Invalid user'));
		}
		$this->set('user', $this->cor_User->read(null, $id));
		
	}
	
	public function login() {
    if ($this->request->is('post')) {		
		$requestUser = mysql_real_escape_string($this->request->data['User']['Username']);
		$requestPwd = mysql_real_escape_string ($this->request->data['User']['Password']);
		
		
		$queryDBPassword = "SELECT UserId, UserType, IsActive, FirstName, Password FROM AxiaCon_Dev.dbo.cor_User where Username='$requestUser'";
		$resultDBPassword = $this->cor_User->query($queryDBPassword);
		if($resultDBPassword)
		{
			$queryInputPassword = "SELECT distinct 'Password'=AxiaCon.dbo._Encrypt('$requestPwd')";
			$resultInputPassword = $this->cor_User->query($queryInputPassword);
		}		
		
		if($resultDBPassword && $resultInputPassword)
		{
			if(($resultInputPassword[0][0]['Password'] == $resultDBPassword[0][0]['Password']) && ($resultDBPassword[0][0]['IsActive'] == 'Y'))
			{
				if($this->Auth->login(array('UserId' => $resultDBPassword[0][0]['UserId'], 'UserType' => $resultDBPassword[0][0]['UserType'], 'UserName' => $resultDBPassword[0][0]['FirstName'])))
				{
					$this->Cookie->write('User.UserId',$resultDBPassword[0][0]['UserId']);
					$this->Cookie->write('User.UserType',$resultDBPassword[0][0]['UserType']);
					$this->Cookie->write('User.Name',$resultDBPassword[0][0]['FirstName']);
					return $this->redirect('/');
				}
			}
		}
        $this->Session->setFlash(__('Invalid username or password, try again'));
		
    }	
}
	public function logout() {
		return $this->redirect($this->Auth->logout());
	}


}
